#!/usr/bin/python3
# author:szw
# 2023年06月27日
# Email:1259577135@qq.com
# desc:

import time
import requests
import json
import os
import shutil
import re
from bs4 import BeautifulSoup
proxies={'http':'127.0.0.1:15732',
         'https':'127.0.0.1:15732'}
def get_page(key_word:str,after=None):

    headers = {
        "authority": "www.behance.net",
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "content-type": "application/json",
        "origin": "https://www.behance.net",
        "referer": "https://www.behance.net/search/images",
        "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41",
        "x-bcp": "d814ff56-c667-441a-8845-e4c1957fffe7",
        "x-requested-with": "XMLHttpRequest"
    }
    cookies = {
        "bcp": "d814ff56-c667-441a-8845-e4c1957fffe7",
    }
    url = "https://www.behance.net/v3/graphql"
    data = {
        "query": "\n      query GetImageSearchResults(\n        $query: query\n        $filter: SearchResultFilter\n        $first: Int!\n        $after: String\n        $similarStyleId: ModuleId\n        $shouldIncludeSimilarStyles: Boolean!\n      ) {\n        search(query: $query, type: IMAGE, filter: $filter, first: $first, after: $after) {\n          pageInfo {\n            hasNextPage\n            endCursor\n          }\n          nodes {\n            ... on ImageModule {\n              __typename\n              id\n              src\n              flexWidth\n              flexHeight\n              height\n              width\n              tags\n              colors {\n                r\n                g\n                b\n              }\n              nftData {\n                contractAddress\n                contractAddressUrl\n                tokenId\n                creatorName\n                creatorUrl\n                imageUrl\n                name\n                description\n              }\n              exifData {\n                makeAndModel {\n                  label\n                  value\n                }\n                lens {\n                  label\n                  value\n                }\n                focalLength {\n                  label\n                  value\n                  searchValue\n                }\n                iso {\n                  label\n                  value\n                }\n                exposureMode {\n                  label\n                  value\n                }\n                shutterSpeed {\n                  label\n                  value\n                  searchValue\n                }\n                aperture {\n                  label\n                  value\n                  searchValue\n                }\n              }\n              project {\n                id\n                slug\n                matureAccess\n                license {\n                  id\n                  label\n                  url\n                  text\n                  images\n                }\n                url\n                name\n                slug\n                isOwner\n                owners {\n                  ...OwnerFields\n                  adobeId\n                  images {\n                    size_50 {\n                      url\n                    }\n                  }\n                }\n                stats {\n                  appreciations {\n                    all\n                  }\n                  views {\n                    all\n                  }\n                  comments {\n                    all\n                  }\n                }\n                tools {\n                  id\n                  title\n                  url\n                  synonym {\n                    iconUrl\n                    downloadUrl\n                    galleryUrl\n                    title\n                  }\n                }\n                fields {\n                  id\n                  label\n                  slug\n                  url\n                }\n                covers {\n                  size_115 {\n                    url\n                  }\n                  size_404 {\n                    url\n                  }\n                }\n              }\n              imageSizes {\n                size_disp {\n                  url\n                  width\n                  height\n                }\n                size_max_632 {\n                  url\n                  width\n                  height\n                }\n                size_max_316 {\n                  url\n                  width\n                  height\n                }\n                size_max_158 {\n                  url\n                  width\n                  height\n                }\n                size_hd {\n                  url\n                  width\n                  height\n                }\n                size_fs {\n                  url\n                  width\n                  height\n                }\n                size_2800_opt_1 {\n                  url\n                  width\n                  height\n                }\n                size_1400_opt_1 {\n                  url\n                  width\n                  height\n                }\n                size_max_1200 {\n                  url\n                  width\n                  height\n                }\n                size_disp_still {\n                  url\n                  width\n                  height\n                }\n                size_2800_still {\n                  url\n                  width\n                  height\n                }\n                size_1400_still {\n                  url\n                  width\n                  height\n                }\n                size_632_still {\n                  url\n                  width\n                  height\n                }\n                size_316_still {\n                  url\n                  width\n                  height\n                }\n                size_158_still {\n                  url\n                  width\n                  height\n                }\n              }\n            }\n          }\n          metaContent {\n            toolCard {\n              cta {\n                text\n                url\n              }\n              description\n              links {\n                text\n                url\n                type\n              }\n              slug\n              title\n            }\n            csam {\n              isCSAMViolation\n              description\n              helpResource\n              reportingOption\n            }\n            followableTag {\n              isFollowing\n              tag {\n                id\n                title\n              }\n            }\n          }\n        }\n\n        imageModule(id: $similarStyleId) @include(if: $shouldIncludeSimilarStyles) {\n          src\n          width\n          height\n          nftData {\n            contractAddress\n            contractAddressUrl\n            tokenId\n            creatorName\n            creatorUrl\n            imageUrl\n            name\n            description\n            isInUserNftProject\n          }\n          project {\n            url\n            owners {\n              ...OwnerFields\n              adobeId\n              images {\n                size_50 {\n                  url\n                }\n              }\n            }\n          }\n          imageSizes {\n            size_max_632 {\n              url\n              width\n              height\n            }\n            size_max_316 {\n              url\n              width\n              height\n            }\n            size_max_158 {\n              url\n              width\n              height\n            }\n          }\n        }\n      }\n      \n  fragment OwnerFields on User {\n    displayName\n    hasPremiumAccess\n    id\n    isFollowing\n    isProfileOwner\n    location\n    locationUrl\n    url\n    username\n    availabilityInfo {\n      availabilityTimeline\n      isAvailableFullTime\n      isAvailableFreelance\n    }\n  }\n\n    ",
        "variables": {
            "query": key_word,
            "filter": {},
            "first": 48,
            # "after": "MjQ1",
            "similarStyleId": 0,
            "shouldIncludeSimilarStyles": False
        }
    }
    if after:
        data["variables"]["after"] = after

    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url,proxies=proxies, headers=headers, cookies=cookies, data=data)
    requests.session().close()
    requests.session().keep_alive = False
    if response.text:
        return response.json()

def get_content_detail(url):
    # url = 'https://www.behance.net/gallery/136862181/Porsche-988R-VISION'
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive",
        "Upgrade-Insecure-Requests": "1",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "cross-site",
        "TE": "trailers"
    }
    cookies = {
        "gki": "{%22feature_creative_cloud_search%22:false%2C%22feature_gql_profile_drafts_request%22:false%2C%22recs_project_search_loggedout%22:false%2C%22feature_hire_include_freelance_activity%22:false}",
        "OptanonAlertBoxClosed": "2023-06-21T06:51:15.418Z",
        "OptanonConsent": "groups=C0001%3A1%2CC0002%3A1%2CC0003%3A1%2CC0004%3A1",
        "AMCV_9E1005A551ED61CA0A490D45%40AdobeOrg": "870038026%7CMCMID%7C09968874126259841161079466337033196426%7CMCAID%7CNONE%7CMCOPTOUT-1688701632s%7CNONE%7CMCAAMLH-1689299232%7C11%7CMCAAMB-1689299232%7Cj8Odv6LonN4r3an7LhD3WZrU1bUpAkFkkiY1ncBR96t2PTI%7CMCCIDH%7C1746874283%7CvVersion%7C5.0.0",
        "_fbp": "fb.1.1687330277516.744444468",
        "g_state": "{\"i_p\":1689219149673,\"i_l\":3}",
        "recent_items": "1=conceptcar|concept%20car|car|%E6%B1%BD%E8%BD%A6%E5%A4%96%E5%9E%8B|%E6%B1%BD%E8%BD%A6%E8%AE%BE%E8%AE%A1",
        "dialog_dismissals": "following_tags_ftux_tooltip%3Bannouncement_36%3Bannouncement_37",
        "sign_up_prompt": "true",
        "bcp": "05a1cf89-a9ce-4f9d-82f1-938cddbd8439",
        "bcp_generated": "1688612688454",
        "gk_suid": "94465981",
        "originalReferrer": "",
        "AMCVS_9E1005A551ED61CA0A490D45%40AdobeOrg": "1",
        "s_cc": "true",
        "s_sq": "%5B%5BB%5D%5D",
        "s_ppv": "[%22www.behance.net/gallery/136862181/Porsche-988R-VISION%22%2C35%2C0%2C2688%2C1334%2C960%2C1920%2C1080%2C1%2C%22P%22]",
        "gpv": "behance.net:gallery",
        "ilo0": "true"
    }
    params = {
        "mt": "login"
    }
    for i in range(5):
        try:
            response = requests.get(url, headers=headers, proxies=proxies, cookies=cookies, params=params)
            return response.text
        except:
            time.sleep(5)
    print(id,'data not get ')
    return None
def parse_content_detail(content):
    soups =BeautifulSoup(content,'lxml')
    try:
        datas =soups.find('div',id ='project-modules').find_all('img')
        return datas
    except:
        return None

if __name__ == '__main__':
    from pprint import pprint
    # main()
    response=(get_page(key_word='conceptcar',after=''))
    print(response['data']['search']['pageInfo']['endCursor'])
    print(response['data']['search']['nodes'])
    # print(response['data']['search']['nodes'][0]['src'])
    # print(response['data']['search']['nodes'][0]['project']['url'])
    # url = 'https://www.behance.net/gallery/136862181/Porsche-988R-VISION'
    # response = get_content_detail(url)

    pass